package endcourseproject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import lejos.nxt.LCD;
import lejos.nxt.Sound;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;

public class NXTBluetooth extends Thread
{	
	private DataMessageListener _listener = null;
	private BTConnection _connection = null;
	private DataInputStream dis = null;
	private DataOutputStream dos = null;
	
	public NXTBluetooth(DataMessageListener listener)
	{
		_listener = listener;

		setDaemon(true);
		start();
	}
	
	public void sendMessage(DataMessage message)
	{
		if(message.isValid())
		{
			// Protect access to _connection
			boolean send = false;
			
			// TODO: Not good!
			//synchronized(this)
			{
				send = _connection != null;	
			}
			
			if(send)
			{
				int len = message.getSize();
				
				try {
					dos.write(message.getBytes(), 0 , len);
					dos.flush();
				} catch (IOException e) {
					Sound.beep();
				}
			}
		}
	}
	
	public void run()
	{	
		DataMessage message = null;
		
		while (true)
		{
			try
			{
				// Lock access (protect _connection and _buffer)
				synchronized(this)
				{	
			
					// Wait for connection if not connected
					if( _connection == null )
					{
						LCD.drawString("waiting", 0, 2);
						LCD.refresh();
						//_connection = Bluetooth.waitForConnection(10000, NXTConnection.RAW);
						_connection = Bluetooth.waitForConnection();
						if( _connection != null)
						{
							dis = _connection.openDataInputStream();
							dos = _connection.openDataOutputStream();
						}
						LCD.drawString("       ", 0, 2);
						LCD.refresh();
					}
				
				
					// Look for data if connected			
					try {
						if( _connection != null )//&& dis.available() >= 2 )
						{
							
							byte b0 = dis.readByte();
							byte b1 = dis.readByte();

							byte[] bytes = new byte[b1+2];
							for( int i = 0 ; i < b1 ; i++)
							{
								bytes[i+2] = dis.readByte();
							}
							bytes[0] = b0;
							bytes[1] = b1;
							
							// Create message
							message = new DataMessage(bytes); 
							
						}
					} catch (IOException e) {
						Sound.beep();
						_connection.close();
						_connection = null;
					}
				} // Release lock
				
				// Signal message received
				if( message != null )
				{
					if( message.isValid() && _listener != null )
					{
						_listener.messageReceived(this, message);
					}
					message = null;
				}
				
				
				
				// Relax
				Thread.sleep(50);
			}
			catch(InterruptedException ex)
			{
				Sound.beep();
			}
		}
	}
	
}
